package com.dbcs.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dbcs.beans.Cliente;
import com.dbcs.beans.Coche;
import com.dbcs.persistencia.DAOCoche;
import com.dbcs.utilidades.LeerPropiedades;

/**
 * Servlet implementation class ServletMostrarVehiculos
 */
@WebServlet("/ServletMostrarVehiculos")
public class ServletMostrarVehiculos extends HttpServlet {
	
	Logger logger = Logger.getLogger("ServletMostrarVehiculos.class");
	
	private static Properties propiedades = new LeerPropiedades().getProperties();
	private static final String URL_MOSTRAR_COCHES = propiedades.getProperty("URL_MOSTRAR_COCHES");
	
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletMostrarVehiculos() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Cliente c = (Cliente) request.getSession().getAttribute("cliente");
		ArrayList<Coche> listaCoches = null;
		
		try{
			DAOCoche d = new DAOCoche();
			
			if (c.getCliente_bloqueado().equals("0"))
				listaCoches = d.listaCoches(c.getCategoria_carnet());
			else
				listaCoches = null;
			
		}catch(SQLException e){
			logger.error("ERROR SQL: "+e);
		}catch(Exception e1){
			logger.error("Excepcion general: "+e1);
			
		}
		
		// Este iterador va para mostrarCoches.jsp
		request.getSession().setAttribute("itCoches", listaCoches.iterator());
		
		
		HashMap<String, Coche> mapaCoche = new HashMap<>();
		Iterator<Coche> itAux = listaCoches.iterator();
		Coche cAux = new Coche();
		while (itAux.hasNext()){
			cAux = itAux.next();
			mapaCoche.put(cAux.getMatricula(), cAux);
		}
		
		
		request.getSession().setAttribute("mapaVehiculos", mapaCoche);
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL_MOSTRAR_COCHES);
		
		dispatcher.forward(request, response);
		
		
	}

}
